<?php
//рус
include_once(_APP_PATH. "business/structure/structure_mapper.php");
class structure_admin_http_web extends controller_prototype_class
{
    private $_actionTitle;
    public $_structMapper;
    
    public $_cid;
    public $_subCat;
    
    private $_pageParamsFieldName = 'page_params';
    private $_moduleParamsFieldName = 'module_params';
    
    protected function ControllerInit()
    {
        $this->_structMapper = StructureMapper::GetInstance($this->User());

        $this->_cid = intval($this->Request()->get('cat')); 
        if (!$this->_cid || !$this->_structMapper->GetById($this->_cid)) 
        {
        	if ($rootElem = $this->_structMapper->GetByUrl('')) $this->_cid = $rootElem->GetId();
        	else $this->_cid = 0;     
        }
        
        $this->_subCat = intval($this->Request()->get('subcat'));
        if ($this->_subCat && !$this->_structMapper->GetById($this->_subCat)) 
        {
        	$this->_subCat = 0;     
        }        
    } 
    protected function PrimaryActionInit ($basicActionName)
    {
        $this->GetModule()->GetDecorator()->SetMenuActiveElement('structure/list')
        								  ->SetSecondAction('Left Sidebar', 'left_block', 'structure'); 
    }        
    /**
		экшен по-умолчанию
	*/
    public function PrAction ()
    {
        $this->out_subcategoriesPr();
    }
    
    protected $_pageParamsCtrl;
    
    public function GetPageParamsCtrl()
    {
    	if (!$this->_pageParamsCtrl)
    	{
	        $this->_pageParamsCtrl = SysLoader::GetModule('controlls', 'http', '_web')->GetCtrl('params');    	    					   		
    	}

    	return $this->_pageParamsCtrl;
    }    

    public function GetCatListTitle ()
    {
        $t = $this->GetTemplator();
        return $t->render('structure/_categories_title.phtml');
    }
    public function catlistScAction ()
    {
        $t = $this->GetTemplator();
        $t->cid = $this->_cid;
        $t->mapper = $this->_structMapper;

        $t->path = array($this->_cid);    
        while (($elem = $this->_structMapper->GetById($t->path[sizeof($t->path) - 1])) && $elem->GetParentId()) 
        {
            $t->path[] = $elem->GetParentId();
        }
        return $t->render('structure/_categories.phtml');
    }
    public function out_subcategoriesPrAction ()
    {
        $t = $this->GetTemplator();
        $t->cid = $this->_cid;
        $t->mapper = $this->_structMapper;
        $t->isSuperUser = $this->User()->IsSuperUser();
        $this->LoadTemplate ($t->render('structure/_subcategories.phtml'));
    }

    public function add_catPrAction ($elementObj = null)
    {
        if (!$elementObj) 
        {
        	if (!$this->_subCat) 
        	{
        		$elementObj = $this->_structMapper->GetDraft();
        		$elementObj->SetParentId($this->_cid);
        	}
        	else $elementObj = $this->_structMapper->GetById($this->_subCat); 
        }
        
        $t = $this->GetTemplator();
        $t->cid = $this->_cid;
        $t->elementObj = $elementObj;
        $t->pageTypes = MozgCfg::GetProp('global/structure//pageTypes');
		$t->mapper = $this->_structMapper;	        
        $t->isSuperUser = $this->User()->IsSuperUser();

        $t->pageParamsBlock = $this->getPageParamsBlock($elementObj->GetPageParams());
        $t->paramFieldsJS = $this->GetPageParamsCtrl()->GetParamsFieldsJS();      
        
        /*  module params  */
        $t->moduleParamsBlock = $this->getModuleParamsBlock($elementObj->GetModuleParams());
        
        $this->LoadTemplate($t->render('structure/_addcat.phtml'));
        
        if ($elementObj->GetDraft()) 
        {
            $this->GetModule()->GetDecorator()->SetMenuActiveElement('structure/add');
        } 
    }
    
    public function getPageParamsBlock($params)
    {
    	$paramsCtrl = $this->GetPageParamsCtrl()->SetFieldArrName($this->_pageParamsFieldName);											
    	return $paramsCtrl->GetFullHtml($params);
    }
    
    public function getModuleParamsBlock($params)
    {
    	$paramsCtrl = $this->GetPageParamsCtrl()->SetFieldArrName($this->_moduleParamsFieldName);									
    	return $paramsCtrl->GetFullHtml($params);										
    }
    
    public function save_catPrAction ()
    {
      	if (!$this->_subCat) $elementObj = $this->_structMapper->GetDraft();
      	else $elementObj = $this->_structMapper->GetById($this->_subCat);        
        
        $elementObj->SetParentId(intval($this->Request()->getPost('parent_cid')));
        $elementObj->SetName($this->Request()->getPost('name'));
        $elementObj->SetUrl($this->Request()->getPost('url'));
        $elementObj->SetActive($this->Request()->getPost('active') ? 1 : 0);
        $elementObj->SetInMenu($this->Request()->getPost('inmenu') ? 1 : 0);
        
        if ($this->isSuperUser || !$elementObj->GetBlocked())
        {
        	$pageType = intval($this->Request()->getPost('page_type'));
	        $elementObj->SetPageType($pageType);
        }

        $pageParams = $elementObj->GetPageParams();
        $pageParams->SetData((array)$this->Request()->getPost($this->_pageParamsFieldName));
        $pageParams->SetData($this->GetPageParamsCtrl()->PreparePostData($pageParams));

        $moduleParams = $elementObj->GetModuleParams();
        $moduleParams->SetData((array)$this->Request()->getPost($this->_moduleParamsFieldName));
        $moduleParams->SetData($this->GetPageParamsCtrl()->PreparePostData($moduleParams));          
        
        if ($this->_structMapper->Save($elementObj)) 
        {
            $this->Libs()->messanger->createMessage('Раздел сохранён');
            
            if ($this->Request()->getPost('gotohtml'))
            {
            	MozgRoute::Get('http')->Redirect(array('module' => 'admin', 'ctrl' => 'structure', 'action' => 'edit_cat_body', 'cat' => $this->_cid , 'subcat' => $elementObj->GetId()));
            }
            else
            {
				MozgRoute::Get('http')->Redirect(array('module' => 'admin', 'ctrl' => 'structure', 'action' => 'out_subcategories', 'cat' => $this->_cid));
            }
		} 
        else 
        {
            $this->Libs()->messanger->createMessage($this->_structMapper->GetErrorMessage(), MESSAGE_ERROR);
            $this->add_catPr($elementObj);
        }
    }
    
    public function del_catPrAction ()
    {
    	$item = $this->_structMapper->GetById($this->_subCat);
    	
    	if (!$item)
    	{
			$this->Libs()->messanger->createMessage('Раздел не найден', MESSAGE_ERROR);    		
    	}
		elseif (!$item->GetBlocked() || $this->User()->IsSuperUser()) 
        {	
	        if (!$this->_structMapper->Delete($item->GetId())) 
	        {
	            $this->Libs()->messanger->createMessage('Не удалось удалить раздел', MESSAGE_ERROR);
	        } 
	        else 
	        {		        	
	            $this->Libs()->messanger->createMessage('Раздел удалён');
	        }   		
        }
        else 
        {
	        $this->Libs()->messanger->createMessage('Невозможно удалить раздел', MESSAGE_ERROR);      	
        }  		
        
        if ($this->_subCat != $this->_cid) $redirectCid = $this->_cid;
        else $redirectCid = $item->GetParentId();
         
        MozgRoute::Get('http')->Redirect(array('module' => 'admin', 'ctrl' => 'structure', 'action' => 'out_subcategories', 'cat' => $redirectCid));
    }
    
    public function edit_cat_bodyPrAction()
    {
       	if (!$this->_subCat) 
       	{
       		MozgRoute::Get('http')->Redirect(array('module' => 'admin', 'ctrl' => 'structure', 'action' => 'out_subcategories', 'cat' => $this->_cid));
       	}
       	else $elementObj = $this->_structMapper->GetById($this->_subCat);     	
    	
        $t = $this->GetTemplator();
        $t->cid = $this->_cid;        
        $t->elementObj = $elementObj;
        $t->mapper = $this->_structMapper;
        $t->body = $this->_structMapper->GetStaticContent($elementObj->GetId());
        $this->LoadTemplate($t->render('structure/_editcatbody.phtml'));
        $this->GetModule()->GetDecorator()->SetSecondAction('Right Sidebar', 'rightContentAccess', 'structure');
    
        $baseUrlParams = array(
        						'module' => 'admin',
        						'ctrl' => $this->GetSelfName(), 
        						'action' => 'media_add_structure', 
        						'cat' => $this->_cid, 
        						'subcat' => $this->_subCat
        					);        
        
        $this->GetModule()->GetDecorator()->SetSecondAction('Left Sidebar', 'media_blockSc', 'media', array('baseUrl' => $baseUrlParams, 'params' => array('contentButton' => true)));    
    }
    
    public function media_add_structurePrAction()
    {
    	$this->edit_cat_body();  	
    }    
    
    public function save_cat_bodyPrAction ()
    {
        $content = $this->Request()->getPost('body');
        $result = $this->_structMapper->SaveStaticContent($this->_subCat, $content);
        
        if (!$result) 
        {
            $this->Libs()->messanger->createMessage('Содержимое не обновлено', MESSAGE_ERROR);
        } 
        else 
        {
            $this->Libs()->messanger->createMessage('Содержимое обновлено');
        }
        
        MozgRoute::Get('http')->Redirect(array('module' => 'admin', 'ctrl' => 'structure', 'action' => 'out_subcategories', 'cat' => $this->_cid));
    }
    public function content_accessScAction ()
    {
       	if (!$this->_subCat) 
       	{
       		return '';
       	}
       	else $elementObj = $this->_structMapper->GetById($this->_subCat);     	

        $t = $this->GetTemplator();
        $t->data = $this->_structMapper->GetContentAccess($this->_subCat);
        $t->elementObj = $elementObj;
        $t->cid = $this->_cid;
        return $t->render('structure/_content_access.phtml');
    }
    
    public function SaveContentAccess()
    {
    	$obj = SysLoader::GetModResponse();
        if (!$this->_subCat) 
       	{
       		$obj->SetMessage('Раздел не найден');
       		$obj->SetStatus(MR_STATUS_ERROR);
       	}  
       	else
       	{  	
	        $isClosed = $this->Request()->has('is_closed') ? 1 : 0;
	        $result = $this->_structMapper->SaveContentAccess($this->_subCat, $isClosed);
	        if (!$result) 
	        {
	            $obj->SetMessage('Доступ не был сохранён');
	            $obj->SetStatus(MR_STATUS_ERROR);
	        } 
	        else 
	        {
	            $obj->SetMessage('Доступ сохранён');
	            $obj->SetStatus(MR_STATUS_OK);	        	
	        }
       	}
       	return $obj;	            	
    }
    
    public function save_content_accessPrAction()
    {
       	$result = $this->SaveContentAccess();

   	    if (!$result) 
        {
            $this->Libs()->messanger->createMessage($result->GetMessage(), MESSAGE_ERROR);
        } 
        else 
        {
            $this->Libs()->messanger->createMessage($result->GetMessage());
        }       	

        MozgRoute::Get('http')->Redirect(array('module' => 'admin', 'ctrl' => 'structure', 'action' => 'edit_cat_body', 'cat' => $this->_cid , 'subcat' => $this->_subCat));
    }
    
    public function UpdateSort()
    {
    	$obj = SysLoader::GetModResponse();
    	
        $catIds = (array)$this->Request()->getPost('scat');
        $result = $this->_structMapper->Sort($catIds);
		if (!$result) 
		{
		    $obj->SetMessage('Произошла ошибка');
		    $obj->SetStatus(MR_STATUS_ERROR);
		} 
		else 
		{
		    $obj->SetMessage('Сортировка сохранена');
		    $obj->SetStatus(MR_STATUS_OK);	        	
		} 

		return $obj;
    }
    
    public function Move()
    {
    	$obj = SysLoader::GetModResponse();

        $catId = intval($this->Request()->getQuery('drag'));
        $parentId = intval($this->Request()->getQuery('drop'));
        
        $item = $this->_structMapper->GetById($catId);

        if (!$item)
        {
            $obj->SetMessage('Раздел не найден');
            $obj->SetStatus(MR_STATUS_ERROR);        	
        }
        else 
        {
        	$item->SetParentId($parentId);
	        $result = $this->_structMapper->Save($item);
	        if ($result) 
	        {
	            $obj->SetMessage('Раздел перемещён');
	            $obj->SetStatus(MR_STATUS_OK);
	        } 
	        else 
	        {
	            $obj->SetMessage($this->_structMapper->GetErrorMessage());
	            $obj->SetStatus(MR_STATUS_ERROR);
	        }
        }
        
        return $obj;
    }    
    
    public function rightContentAccess ()
    {
        $t = $this->GetTemplator();
        $t->title = 'Доступ к содержимому';
        $t->content = $this->content_accessSc();
        return $t->render('_right_block_template.phtml');
    }
    
    public function left_block ()
    {
        $t = $this->GetTemplator();
        $t->title = $this->GetCatListTitle();
        $t->content = $this->catlistSc();
        return $t->render('_left_block_template.phtml');
    }
    
    protected function LoadTemplate ($content)
    {
        $t = $this->GetTemplator();
        $t->title = $this->GetPathTitle();
        $t->content = $content;
        $this->Response()->SetBody($t->render('_main_block_template.phtml'));
    }
    
    protected function GetPathTitle ()
    {
        $t = $this->GetTemplator();
        $t->mapper = $this->_structMapper;
        $t->actionTitle = $this->_actionTitle;
        $t->cid = $this->_cid;
        return $t->render('structure/_path_title.phtml');
    }   
}